﻿#include <iostream>
#include <fstream>
#include <cstring>
#include <arpa/inet.h>
#include <unistd.h>

#define PORT 12345
#define CHUNK_SIZE 1024

void sendFile(const char* filename) {
    int serverSock, clientSock;
    struct sockaddr_in serverAddr, clientAddr;
    char buffer[CHUNK_SIZE];
    socklen_t clientLen = sizeof(clientAddr);

    // 创建套接字
    if ((serverSock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        perror("socket");
        exit(1);
    }

    // 配置服务器地址
    memset(&serverAddr, 0, sizeof(serverAddr));
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_addr.s_addr = INADDR_ANY;
    serverAddr.sin_port = htons(PORT);

    // 绑定套接字
    if (bind(serverSock, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) < 0) {
        perror("bind");
        close(serverSock);
        exit(1);
    }

    // 监听连接
    if (listen(serverSock, 1) < 0) {
        perror("listen");
        close(serverSock);
        exit(1);
    }

    std::cout << "等待客户端连接..." << std::endl;

    // 接受客户端连接
    if ((clientSock = accept(serverSock, (struct sockaddr*)&clientAddr, &clientLen)) < 0) {
        perror("accept");
        close(serverSock);
        exit(1);
    }

    std::cout << "客户端已连接。" << std::endl;

    // 打开文件
    std::ifstream file(filename, std::ios::binary);
    if (!file.is_open()) {
        perror("打开文件失败");
        close(clientSock);
        close(serverSock);
        exit(1);
    }

    // 逐块读取文件并发送
    while (!file.eof()) {
        file.read(buffer, CHUNK_SIZE);
        size_t bytesRead = file.gcount();

        if (send(clientSock, buffer, bytesRead, 0) < 0) {
            perror("send");
            break;
        }
    }

    std::cout << "文件发送完成。" << std::endl;

    file.close();
    close(clientSock);
    close(serverSock);
}

int main() {
    const char* filename = "largefile.dat"; // 要发送的文件
    sendFile(filename);
    return 0;
}
